package sfeir.authform.server;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sfeir.authform.client.dao.AuthUser;
import sfeir.authform.server.authservice.AuthService;
import sfeir.authform.server.authservice.AuthServiceFactory;
import sfeir.authform.server.authservice.standard.AuthStandard;

public class AuthServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 5240776791604785826L;    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    
    // /__authService/signup?email=toto@toto.com&password=toto&nickname=toto&name=titi
    // /__authService/login?return=/test.jsp&email=toto@toto.com&password=toto
    @SuppressWarnings("unchecked")
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(true);
        // Get the Return URL (parameter return)
        String url = req.getPathInfo();
        String ret = req.getParameter("return");
        if (ret == null || ret.isEmpty()) {
            ret = "/";
        }
        // Login page (parameter : email, password)
        if (url.equals("/login")) {
            String email = req.getParameter("email");
            String password = req.getParameter("password");
            if (password != null && !password.isEmpty()) {
                password = md5(password);
            }
            else {
                password = req.getParameter("password_md5");
            }
            if (email != null && !email.isEmpty() && password != null && !password.isEmpty()) {
                new AuthStandard(session).login(email, password);
            }
        }
        // Signup page (parameter : email, password)
        else if (url.equals("/signup")) {
            String email = req.getParameter("email");
            String password = req.getParameter("password");
            if (password != null && !password.isEmpty()) {
                password = md5(password);
            }
            else {
                password = req.getParameter("password_md5");
            }
            if (email != null && !email.isEmpty() && password != null && !password.isEmpty()) {
                AuthUser user = new AuthUser();
                user.setEmail(email);
                user.setPassword(password);
                user.setNickname(req.getParameter("nickname"));
                user.setAuthDomain(req.getHeader("Host"));
                Enumeration paramNames = req.getParameterNames();
                while(paramNames.hasMoreElements()) {
                  String paramName = (String) paramNames.nextElement();
                  if (!paramName.equals("email") && !paramName.equals("password") && !paramName.equals("password_md5") && !paramName.equals("nickname") && !paramName.equals("return"))
                  {
                      user.setField(paramName, req.getParameter(paramName));
                  }
                }
                new AuthStandard(session).signup(user);
            }
        }
        else if (url.equals("/logout")) {
            new AuthStandard(session).logout();
        }
        resp.sendRedirect(ret);
    }
    
    public static String md5(String key) {
      byte[] uniqueKey = key.getBytes();
      byte[] hash = null;
      try {
          hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
      }
      catch (NoSuchAlgorithmException e) {
          throw new Error("no MD5 support in this VM");
      }
      StringBuffer hashString = new StringBuffer();
      for (int i = 0; i < hash.length; ++i) {
          String hex = Integer.toHexString(hash[i]);
          if (hex.length() == 1) {
              hashString.append('0');
              hashString.append(hex.charAt(hex.length() - 1));
          }
          else {
              hashString.append(hex.substring(hex.length() - 2));
          }
      }
      return hashString.toString();
  }
}
